<template>
  <div class="app-container">
    <el-main id="main-content">
      <div class="content-wrapper">
        <!-- 搜索和操作区域 -->
        <div class="operation-area">
          <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
            <el-form-item>
              <el-input v-model="queryParams.keyword" placeholder="请输入土地ID或位置" clearable @keyup.enter="handleSearch">
                <template #append>
                  <el-button :icon="Search" @click="handleSearch"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <!-- <el-form-item>
              <el-select v-model="queryParams.state" placeholder="土地状态" clearable @change="handleSearch">
                <el-option label="正常" :value="0" />
                <el-option label="已售出" :value="1" />
                <el-option label="已删除" :value="-1" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
              <el-button type="success" @click="handleAdd">添加土地</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 表格区域 -->
        <el-table 
          v-loading="loading" 
          :data="tableData" 
          border 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="landid" label="土地ID" width="80" />
          <el-table-column prop="position" label="土地位置" min-width="120" />
          <el-table-column prop="farmer" label="农户姓名" min-width="100" />
          <el-table-column prop="area" label="面积" width="80">
            <template #default="scope">
              {{ scope.row.area }}㎡
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="100">
            <template #default="scope">
              {{ scope.row.price }}元
            </template>
          </el-table-column>
          <el-table-column prop="discount" label="优惠价" width="100">
            <template #default="scope">
              {{ scope.row.discount }}元
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="80" />
          <el-table-column prop="createtime" label="创建时间" min-width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createtime) }}
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStateType(scope.row.state)">
                {{ getStateText(scope.row.state) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleDetail(scope.row)">详情</el-button>
              <el-button type="success" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                type="danger" 
                link 
                @click="handleDelete(scope.row)" 
                v-if="scope.row.state !== -1">删除</el-button>
              <el-button 
                type="warning" 
                link 
                @click="handleUpdateState(scope.row, 0)" 
                v-if="scope.row.state === -1">恢复</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <!-- 土地表单对话框 -->
        <el-dialog
          :title="dialogTitle"
          v-model="dialogVisible"
          width="600px"
          @close="dialogClose"
        >
          <el-form
            ref="landFormRef"
            :model="landForm"
            :rules="formRules"
            label-width="100px"
          >
            <el-form-item label="土地位置" prop="position">
              <el-input v-model="landForm.position" placeholder="请输入土地位置" />
            </el-form-item>
            <el-form-item label="农户姓名" prop="farmer">
              <el-input v-model="landForm.farmer" placeholder="请输入农户姓名" />
            </el-form-item>
            <el-form-item label="土地面积" prop="area">
              <el-input-number v-model="landForm.area" :min="1" :precision="0" controls-position="right" />
              <span class="unit">㎡</span>
            </el-form-item>
            <el-form-item label="图片路径" prop="img">
              <el-input v-model="landForm.img" placeholder="请输入图片路径" />
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="landForm.price" :min="1"  :step="1" controls-position="right" />
              <span class="unit">元</span>
            </el-form-item>
            <el-form-item label="优惠价" prop="discount">
              <el-input-number v-model="landForm.discount" :min="0"  :step="1" controls-position="right" />
              <span class="unit">元</span>
            </el-form-item>
            <el-form-item label="库存" prop="stock">
              <el-input-number v-model="landForm.stock" :min="0" :precision="0" controls-position="right" />
            </el-form-item>
            <el-form-item label="土地信息" prop="info">
              <el-input 
                v-model="landForm.info" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入土地详细信息描述" 
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 土地详情对话框 -->
        <el-dialog
          title="土地详情"
          v-model="detailVisible"
          width="700px"
        >
          <el-descriptions :column="2" border v-if="detailData">
            <el-descriptions-item label="土地ID">{{ detailData.landid }}</el-descriptions-item>
            <el-descriptions-item label="土地位置">{{ detailData.position }}</el-descriptions-item>
            <el-descriptions-item label="农户姓名">{{ detailData.farmer }}</el-descriptions-item>
            <el-descriptions-item label="土地面积">{{ detailData.area }}㎡</el-descriptions-item>
            <el-descriptions-item label="价格">{{ detailData.price }}元</el-descriptions-item>
            <el-descriptions-item label="优惠价">{{ detailData.discount }}元</el-descriptions-item>
            <el-descriptions-item label="库存">{{ detailData.stock }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStateType(detailData.state)">
                {{ getStateText(detailData.state) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDate(detailData.createtime) }}</el-descriptions-item>
            <el-descriptions-item label="图片" :span="2">
              <el-image 
                style="max-width: 100%; max-height: 200px" 
                :src="detailData.img" 
                fit="cover"
                :preview-src-list="[detailData.img]"
              >
                <template #error>
                  <div class="image-error">图片加载失败</div>
                </template>
              </el-image>
            </el-descriptions-item>
            <el-descriptions-item label="土地信息" :span="2">{{ detailData.info }}</el-descriptions-item>
          </el-descriptions>
        </el-dialog>
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import http from '@/utils/request'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  state: null
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const selectedRows = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('') 
const dialogTitle = ref('')
const landFormRef = ref(null)
const landForm = reactive({
  landid: undefined,
  position: '',
  farmer: '',
  area: 100,
  img: '',
  price: 1000,
  discount: 900,
  stock: 5,
  info: ''
})

// 表单验证规则
const formRules = {
  position: [
    { required: true, message: '请输入土地位置', trigger: 'blur' }
  ],
  farmer: [
    { required: true, message: '请输入农户姓名', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入土地面积', trigger: 'blur' }
  ],
  img: [
    { required: true, message: '请输入图片路径', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入优惠价', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' }
  ],
  info: [
    { required: true, message: '请输入土地信息', trigger: 'blur' }
  ]
}

// 详情对话框
const detailVisible = ref(false)
const detailData = ref(null)

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-');
}

// 获取状态类型
const getStateType = (state) => {
  switch (state) {
    case 0: return 'success'; // 正常
    case 1: return 'warning'; // 已售出
    case -1: return 'danger'; // 已删除
    default: return 'info';
  }
}

// 获取状态文本
const getStateText = (state) => {
  switch (state) {
    case 0: return '正常';
    case 1: return '已售出';
    case -1: return '已删除';
    default: return '未知';
  }
}

// 获取表格数据
const getTableData = () => {
  loading.value = true;
  
  // 根据查询条件决定API路径
  let apiUrl = '/land/list';
  if (queryParams.state !== null) {
    apiUrl = `/land/list/state/${queryParams.state}`;
  }
  
  http.get(apiUrl)
    .then(res => {
      if (res.code === 200) {
        // 过滤关键字
        let filteredData = res.data || [];
        if (queryParams.keyword) {
          const keyword = queryParams.keyword.toLowerCase();
          filteredData = filteredData.filter(item => 
            item.landid.toString().includes(keyword) || 
            (item.position && item.position.toLowerCase().includes(keyword))
          );
        }
        
        // 保存总数量
        total.value = filteredData.length;
        
        // 前端分页处理
        const start = (queryParams.pageNum - 1) * queryParams.pageSize;
        const end = start + queryParams.pageSize;
        tableData.value = filteredData.slice(start, end);
      } else {
        ElMessage.error(res.message || '获取数据失败');
      }
    })
    .catch(error => {
      console.error('获取数据失败:', error);
      ElMessage.error('获取数据失败：' + error.message);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 搜索方法
const handleSearch = () => {
  queryParams.pageNum = 1;
  getTableData();
};

// 重置查询
const resetQuery = () => {
  queryParams.keyword = '';
  queryParams.state = null;
  queryParams.pageNum = 1;
  getTableData();
};

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getTableData();
};

const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getTableData();
};

// 多选操作
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 添加土地
const handleAdd = () => {
  dialogType.value = 'add';
  dialogTitle.value = '添加土地';
  dialogVisible.value = true;
  
  // 初始化表单
  landForm.landid = undefined;
  landForm.position = '';
  landForm.farmer = '';
  landForm.area = 100;
  landForm.img = '';
  landForm.price = 1000;
  landForm.discount = 900;
  landForm.stock = 5;
  landForm.info = '';
};

// 编辑土地
const handleEdit = (row) => {
  dialogType.value = 'edit';
  dialogTitle.value = '编辑土地';
  dialogVisible.value = true;
  
  // 填充表单数据
  Object.assign(landForm, {
    landid: row.landid,
    position: row.position,
    farmer: row.farmer,
    area: row.area,
    img: row.img,
    price: row.price,
    discount: row.discount,
    stock: row.stock,
    info: row.info
  });
};

// 查看详情
const handleDetail = (row) => {
  detailVisible.value = true;
  
  // 获取土地详情
  http.get(`/land/${row.landid}`)
    .then(res => {
      if (res.code === 200) {
        detailData.value = res.data;
      } else {
        ElMessage.error(res.message || '获取详情失败');
      }
    })
    .catch(error => {
      console.error('获取详情失败:', error);
      ElMessage.error('获取详情失败：' + error.message);
    });
};

// 删除土地
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该土地吗？将会改变土地状态为删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    http.delete(`/land/delete/${row.landid}`)
      .then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功');
          getTableData();
        } else {
          ElMessage.error(res.message || '删除失败');
        }
      })
      .catch(error => {
        console.error('删除失败:', error);
        ElMessage.error('删除失败：' + error.message);
      });
  }).catch(()=>{
    ElMessage.info('已取消删除操作');
  });
};

// 更新土地状态
const handleUpdateState = (row, state) => {
  const stateText = state === 0 ? '恢复' : (state === 1 ? '设为已售出' : '删除');
  
  ElMessageBox.confirm(`确认要${stateText}该土地吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    http.put(`/land/state/${row.landid}/${state}`)
      .then(res => {
        if (res.code === 200) {
          ElMessage.success(`${stateText}成功`);
          getTableData();
        } else {
          ElMessage.error(res.message || `${stateText}失败`);
        }
      })
      .catch(error => {
        console.error(`${stateText}失败:`, error);
        ElMessage.error(`${stateText}失败：` + error.message);
      });
  });
};

// 提交表单
const submitForm = () => {
  if (!landFormRef.value) return;
  
  landFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 添加土地
        http.post('/land/add', landForm)
          .then(res => {
            if (res.code === 200) {
              ElMessage.success('添加成功');
              dialogVisible.value = false;
              getTableData();
            } else {
              ElMessage.error(res.message || '添加失败');
            }
          })
          .catch(error => {
            console.error('添加失败:', error);
            ElMessage.error('添加失败：' + error.message);
          });
      } else {
        // 更新土地
        http.put('/land/update', landForm)
          .then(res => {
            if (res.code === 200) {
              ElMessage.success('更新成功');
              dialogVisible.value = false;
              getTableData();
            } else {
              ElMessage.error(res.message || '更新失败');
            }
          })
          .catch(error => {
            console.error('更新失败:', error);
            ElMessage.error('更新失败：' + error.message);
          });
      }
    }
  });
};

// 对话框关闭
const dialogClose = () => {
  landFormRef.value?.resetFields();
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.search-form :deep(.el-form-item) {
  margin-right: 10px;
}

.unit {
  margin-left: 8px;
  color: #666;
}

.image-error {
  background: #f5f7fa;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px;
  width: 100%;
}
</style>